// pages/user/prizes/prizes.ts
import { goToPage, PAGES } from '../../../config/pages';
import { getStoreIntegralList, getStoreIntegralCategory, createIntegralOrder } from '../../../api/points_mall.js';
import userManager from '../../../utils/userManager.js';

Page({
  data: {
    userPoints: 0,
    showAddressModal: false,
    currentProduct: null as any,
    recipientInfo: {
      name: '',
      phone: '',
      address: ''
    },
    // 商品数据
    products: [] as any[],
    loading: false,
    // 分类数据
    categories: [] as any[],
    currentCategory: 'all',
    currentCategoryName: '全部商品',
    showCategoryModal: false,
    categoryLoading: false
  },

  onLoad() {
    this.setNavigationBar();
    this.loadUserPoints();
    this.loadCategories();
    this.loadProducts();
  },

  // 设置导航栏
  setNavigationBar() {
    wx.setNavigationBarTitle({
      title: '积分商城'
    });
  },

  // 页面显示时设置导航栏右侧按钮
  onShow() {
    // 每次显示页面时重新加载数据，确保数据最新
    this.loadUserPoints();
    this.loadProducts();
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#0052d9'
    });
  },

  // 加载用户积分数据
  async loadUserPoints() {
    try {
      // 从用户信息中获取积分数据（integral 字段）
      // 使用强制刷新确保获取最新数据
      const userInfo = await userManager.getUserInfo(true, false);
      const userPoints = (userInfo as any)?.integral || 0;
      
      this.setData({ userPoints });
    } catch (error) {
      console.error('加载积分数据失败:', error);
      // 保持默认值
    }
  },

  // 加载分类数据
  async loadCategories() {
    try {
      this.setData({ categoryLoading: true });
      
      const result = await getStoreIntegralCategory();
      console.log('分类数据result:', result);
      console.log('分类数据result.data:', result.data);
      
      if (result && result.data && Array.isArray(result.data)) {
        // 处理分类数据，添加"全部"选项
        const categories = [
          { id: 'all', cate_name: '全部商品', is_show: 1 },
          ...result.data.filter((item: any) => item.is_show === 1)
        ];
        
        console.log('处理后的分类数据:', categories);
        
        this.setData({ 
          categories
        });
        
        // 更新当前分类名称
        const { currentCategory } = this.data;
        const category = categories.find((item: any) => item.id === currentCategory);
        const categoryName = category ? (category as any).cate_name : '全部商品';
        this.setData({
          currentCategoryName: categoryName
        });
        
        console.log('设置分类数据后的data.categories:', this.data.categories);
      } else {
        console.log('分类数据格式不正确:', result);
        // 设置默认分类
        this.setData({
          categories: [
            { id: 'all', cate_name: '全部商品', is_show: 1 }
          ]
        });
      }
    } catch (error) {
      console.error('加载分类数据失败:', error);
      // 设置默认分类
      this.setData({
        categories: [
          { id: 'all', cate_name: '全部商品', is_show: 1 }
        ]
      });
    } finally {
      this.setData({ categoryLoading: false });
    }
  },

  // 加载商品数据
  async loadProducts() {
    try {
      this.setData({ loading: true });
      
      // 根据当前分类筛选商品
      const params: any = {};
      if (this.data.currentCategory !== 'all') {
        params.cate_id = this.data.currentCategory;
      }
      
      const result = await getStoreIntegralList(params);
      console.log('商品数据result:', result);
      if (result.data) {
        // 处理商品数据
        const products = result.data.map((item: any) => ({
          id: item.id,
          name: item.title,
          points: item.price,
          icon: item.icon || 'fas fa-gift',
          image: item.image,
          description: item.description
        }));
        console.log('商品数据products:', products);
        
        this.setData({ 
          products
        });
      }
    } catch (error) {
      console.error('加载商品数据失败:', error);
      wx.showToast({
        title: '加载商品失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },




  // 立即兑换
  onExchange(e: any) {
    const product = e.currentTarget.dataset.product;
    
    if (this.data.userPoints < product.points) {
      wx.showToast({
        title: '积分不足',
        icon: 'none'
      });
      return;
    }

    this.setData({ 
      currentProduct: product,
      showAddressModal: true 
    });
  },

  // 关闭收货信息模态框
  closeAddressModal() {
    this.setData({ 
      showAddressModal: false,
      currentProduct: null,
      recipientInfo: { name: '', phone: '', address: '' }
    });
  },

  // 处理弹窗遮罩层点击
  onModalOverlayTap(e: any) {
    // 只有点击遮罩层本身才关闭弹窗，点击弹窗内容不关闭
    if (e.target === e.currentTarget) {
      this.closeAddressModal();
    }
  },


  // 输入收货信息
  onRecipientInput(e: any) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [`recipientInfo.${field}`]: e.detail.value
    });
  },

  // 确认兑换
  async confirmExchange() {
    const { currentProduct, recipientInfo } = this.data;
    
    if (!recipientInfo.name || !recipientInfo.phone || !recipientInfo.address) {
      wx.showToast({
        title: '请填写完整收货信息',
        icon: 'none'
      });
      return;
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(recipientInfo.phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return;
    }

    // 参考原型，直接确认兑换
    try {
      wx.showLoading({ title: '提交中...' });
      
      // 调用API创建订单
      const orderData = {
        productId: currentProduct?.id,
        recipientName: recipientInfo.name,
        recipientPhone: recipientInfo.phone,
        recipientAddress: recipientInfo.address
      };
      
      await createIntegralOrder(orderData);
      
      wx.hideLoading();
      wx.showToast({
        title: '兑换成功！商品将尽快给您发货',
        icon: 'success',
        duration: 3000
      });
      
      // 关闭模态框
      this.closeAddressModal();
      
      // 强制刷新用户数据（包括积分）
      await userManager.refreshAfterUpdate('积分兑换');
      
      // 重新加载积分数据
      this.loadUserPoints();
      
    } catch (error: any) {
      wx.hideLoading();
      console.error('兑换失败:', error);
      wx.showToast({
        title: error.message || '兑换失败，请稍后重试',
        icon: 'none'
      });
    }
  },

  // 查看兑换记录
  goToExchangeHistory() {
    goToPage(PAGES.MY_EXCHANGES);
  },

  // 打开分类选择模态框
  openCategoryModal() {
    console.log('打开分类模态框，当前分类数据:', this.data.categories);
    this.setData({ showCategoryModal: true });
  },

  // 关闭分类选择模态框
  closeCategoryModal() {
    this.setData({ showCategoryModal: false });
  },

  // 选择分类
  selectCategory(e: any) {
    const categoryId = e.currentTarget.dataset.categoryId;
    const categoryName = e.currentTarget.dataset.categoryName;
    
    this.setData({
      currentCategory: categoryId,
      currentCategoryName: categoryName,
      showCategoryModal: false
    });
    
    // 重新加载商品数据
    this.loadProducts();
  },

  // 更新当前分类名称
  updateCurrentCategoryName() {
    const { categories, currentCategory } = this.data;
    const category = categories.find((item: any) => item.id === currentCategory);
    const categoryName = category ? (category as any).cate_name : '全部商品';
    
    this.setData({
      currentCategoryName: categoryName
    });
  },

  // 获取当前分类名称
  getCurrentCategoryName() {
    const { categories, currentCategory } = this.data;
    const category = categories.find((item: any) => item.id === currentCategory);
    return category ? (category as any).cate_name : '全部商品';
  }
});